'use strict';
import React, { Component} from 'react';
import {
    View,
    TouchableOpacity,
    StyleSheet,
    ScrollView,
    Modal,
    Platform,
    PixelRatio,
    Dimensions
} from 'react-native';   

import PropTypes from "prop-types";

import Radio from'../radio';
import CheckBox from'../checkBox';
import Badge from'../badge';
import Label from'../label';
import Color from '../../config/theme/standard/color';



export default class Menu extends Component{
    constructor(props) {
        super(props);
        this.state = {
            index: this.props.defaultIndex,
            data: this.props.data,
            prevPropsData: this.props.data,
            pressIndex: 0,
            pressFlag: false,
            modalVisible: false,
            flag: false,
            isWideScreen: false // 鸿蒙适配是否宽屏
        }
    }

    componentDidMount() {
        // 适配鸿蒙折叠屏动态更新组件
        this.addEventListenerScreenWidth = Dimensions.addEventListener('change', this.setIsWideScreen)
    }
    componentWillUnmount() {
        // 适配鸿蒙折叠屏动态更新组件
        if (this.addEventListenerScreenWidth) {
            this.addEventListenerScreenWidth = null
        }
    }
    setIsWideScreen = () => {
        const screenWidth = Dimensions.get('window').width;
        if (screenWidth) {
            this.setState({
                isWideScreen: screenWidth > 500 && screenWidth < 800
            })
        }
    }

    static getDerivedStateFromProps(nextProps, prevState) {
        if (('data' in nextProps) && (nextProps.data !== prevState.data)) {
            return {
                prevPropsData: nextProps.data,
                data: nextProps.data
            };
        }
        return null;
    }


    _show (){
        //this.modalbox.open();
        this.setState({modalVisible:true})
    };

    _close(){
        //this.modalbox.close();
        this.setState({modalVisible:false})
    }

    //创建菜单
    _createItem (){
        let {data,type}=this.props;
        if(this.props.type == 1){
            if(this.props.style == 'radio'){
                return this._radioItem(data,type);
            }else if(this.props.style == 'checkbox'){
                return this._checkBoxItem(data);
            }
        }else if(this.props.type == 2){
            // 二级菜单
            let { height } = this.props;
            height = height ? height : Dimensions.get('window').height * 0.6
            const container = [styles.container];
            let rightMenuStyle = [styles.rightMenuStyle]
            rightMenuStyle.push({
                width: rightMenuStyle.width ? rightMenuStyle.width : (Dimensions.get('window').width - 160)
            })
            container.push({ height: height });
            let comp = null;
            if (Platform.OS == "web") {
                comp = (
                    <ScrollView
                        style={styles.container}
                        alwaysBounceVertical={false}
                        bounces={false}
                        scrollEventThrottle={1}
                        onScrollEndDrag={() => {
                            this.setState({ flag: !this.state.flag })
                        }}
                    >
                        <View style={{ width: '100%', height: '100%', flex: 1, flexDirection: 'row' }}>
                            <ScrollView
                                style={[...rightMenuStyle, { height: '100%', }]}
                                bounces={false}
                                showsVerticalScrollIndicator = {false}
                                scrollEventThrottle={1}
                                onScrollEndDrag={()=>{
                                this.setState({flag:!this.state.flag})
                            }}
                                >
                                {this._radioItem(data,type)}
                                {Platform.OS=='ios'?null:<View style={{height:44}}></View>}
                            </ScrollView>
                            <ScrollView
                                style={[...rightMenuStyle, { height: '100%', }]}
                                bounces={false}
                                showsVerticalScrollIndicator = {false}
                                scrollEventThrottle={1}
                                onScrollEndDrag={()=>{
                                this.setState({flag:!this.state.flag})
                            }}
                                >
                                {this._itemList()}
                                {Platform.OS=='ios'?null:<View style={{height:44}}></View>}
                            </ScrollView>
                        </View>
                    </ScrollView>
                );
            }else{
                comp=(
                    <View style={styles.container}>
                        <ScrollView
                            style={styles.leftMenuStyle}
                            bounces = {false}
                            showsVerticalScrollIndicator = {false}
                            >
                            {this._radioItem(data,type)}
                            {Platform.OS=='ios'?null:<View style={{height:44}}></View>}
                        </ScrollView>
                        <ScrollView
                            style={[...rightMenuStyle]}
                            bounces={false}
                            showsVerticalScrollIndicator={false}
                        >
                            {this._itemList()}
                            {Platform.OS=='ios'?null:<View style={{height:44}}></View>}
                        </ScrollView>
                    </View>
                );

            }
            return comp;
        }
    }

    //创建二级单选菜单的子菜单
    _itemList(){
        let {data}=this.props;
        let {index}=this.state;
        if(data.length == 0) {
            return false;
        };
        if(this.props.style == 'radio'){
            return data.map((item, i) => {
                if(i==index){
                    return this._createMenuRadioItem(item.item);
                };
            })
        }else if(this.props.style == 'checkbox'){
            return data.map((item, i) => {
                if(i==index){
                    return this._checkBoxItem(item.item);
                };
            })
        }
    }

    _createMenuRadioItem(data){
        if(data.length == 0) {
            return false;
        };

        let colorTmp = null;
        let len = this.state.data.length;
        let style = this.props.type == 2 ? { borderLeftWidth: 1 / PixelRatio.get() } : null;
        let dataLength = data.length;
        return data.map((item, i) => {
            colorTmp = item.checked ? 'main' : 'normal';
            let borderStyle = i == (dataLength - 1) ? { borderColor: Color.border } : { borderColor: Color.background };
            let newComponent = null;

            let itemStyle = [styles.item]
            let listStyle = [styles.listWidth]
            itemStyle.push({
                width: itemStyle.width ? itemStyle.width : (Dimensions.get('window').width)
            })
            listStyle.push({
                width: listStyle.width ? listStyle.width : (Dimensions.get('window').width - 160)
            })

            if (Platform.OS == 'web') {
                newComponent = (
                    <TouchableOpacity
                        activeOpacity={1}
                        onClick={() => this._menuItemClick(i)}
                        key={i}
                    >
                        <View style={[...itemStyle, ...listStyle, i >= len ? style : null, borderStyle]}>
                            <Label text={item['label'] ? item['label'] : item} type={'button'} color={colorTmp} />
                        </View>
                    </TouchableOpacity>
                )
            } else {
                newComponent = (
                    <TouchableOpacity
                        activeOpacity={1}
                        onPress={() => this._menuItemClick(i)}
                        key={i}
                    >
                        <View style={[...itemStyle, ...listStyle, i >= len ? style : null, borderStyle]}>
                            <Label text={item['label'] ? item['label'] : item} type={'button'} color={colorTmp} />
                        </View>
                    </TouchableOpacity>
                )
            }
            return newComponent;
        })
    }
    //二级单选菜单的子菜单的点击事件
    _menuItemClick(i){
        let {index,data}=this.state;
        this.setState({
            data:data.map((ele,n)=>{
                if(n==index){
                    ele.item.map((current,num)=>{
                        if(i==num){
                            current.checked=true;
                        }else{
                            current.checked=false;
                        }
                        return current
                    })
                };
                return ele;
            })
        });

        this._close();

        if(typeof this.props.onPress ==  'function'){
            this.props.onPress(index,data[index].item[i]);
        };
    }


    // 单选
    _radioItem(data,type){
        let radioItem = null;

        if(this.props.textAlign == 'left' && type==1){
            radioItem = <View>
                <Radio
                    initial={this.state.index}
                    radio_props={this.props.data}
                    labelBefore={true}
                    onPress={(index) => this._onPress(index)}
                    />
            </View>;
        }else{
            radioItem = this._centerItem(data,type);
        }
        return radioItem;
    }

    _centerItem(data,type){
        if(data.length == 0) {
            return false;
        };

        return data.map((item, i) => {
            let colorTmp = null;
            let bg=null;
            let label=null;
            let style={};
            if(this.state.pressFlag && this.state.pressIndex == i){
                colorTmp = 'press';
            }else{
                colorTmp = this.state.index == i ? 'main' : 'normal';
                if(type==2){
                    bg = this.state.index == i ? 'rgba(255,255,255,1)' : '#f7f7f7';
                }else{
                    bg = this.state.index == i ? 'rgba(255,255,255,1)' : 'rgba(229,229,229,0.3)';
                }
                style = this.state.index == i ? {borderRightWidth:0} : {borderRightWidth:1 / PixelRatio.get()};
            };
            if(item.label){
                label= <Label text={item['label'] ? item['label'] : item} type={'button'} color={colorTmp}/>
            }else if(item.menu){
                label=<View style={{marginRight:12}}>
                    <Label text={item['menu'] ? item['menu'] : item} type={'button'} color={colorTmp}/>
                    {item.badgeText?<Badge dotStyle={[styles.dotStyle, Platform.OS == 'harmony' &&{ zIndex:1 }]}  text={item.badgeText}/>:null}
                </View>
            };

            return (
                <TouchableOpacity
                    activeOpacity={1}
                    onPressIn={() => this._onPressIn(i)}
                    onPressOut={() => this._onPressOut()}
                    onPress={() => this._onPress(i)}
                    key={i}
                    >
                    <View style={[styles.item,type==2?styles.menuItemWidth:null,{backgroundColor:bg},style]}>
                        {label}
                    </View>
                </TouchableOpacity>
            )
        })
    }

    _checkBoxItem(data){
        if(data.length == 0) {
            return false;
        };
        let len=this.state.data.length;
        let style=this.props.type==2?{borderLeftWidth:1 / PixelRatio.get()}:null;
        let widthFlag,widthLabel;
        if(this.props.type==1){
            widthFlag="0"
        }else if(this.props.type==2){
            widthFlag="1"
            widthLabel=Dimensions.get('window').width-160-50;
        }

        return data.map((item, i) => {
            return (
                <View style={[styles.checkBoxItem,i>=len?style:null,{backgroundColor:'white'}]} key={i}>
                    <CheckBox
                        label = {item.label}
                        value = {item.value}
                        labelBefore = {true}
                        isChecked = {item.checked}
                        onChange={(checked,value) => this._onCheckBoxChange(checked,value)}
                        isChange={true}
                        widthFlag={widthFlag}
                        widthLabel={widthLabel}
                        />
                </View>
            )
        })
    }
    // 多选底部按钮
    _bottomItem(){
        let bottomItem = null;
        let buttonContainerStyle = [styles.buttonContainer]
        buttonContainerStyle.push({
            width: buttonContainerStyle.width ? buttonContainerStyle.width : Dimensions.get('window').width
        })
        if (this.props.style == 'checkbox') {
            bottomItem = <View style={[...buttonContainerStyle]}>
                <TouchableOpacity
                    activeOpacity={1}
                    style={[styles.button,{borderRightWidth:1 / PixelRatio.get()}]}
                    onPress={()=>this._onReset()}
                    >
                    <Label text={'重置'} color={'fill'} type={'button'}/>
                </TouchableOpacity>
                <TouchableOpacity
                    activeOpacity={1}
                    style={styles.button}
                    onPress={()=>this._onConfirm()}
                    >
                    <Label text={'确定'} color={'main'} type={'button'}/>
                </TouchableOpacity>
            </View>;
        }
        return bottomItem;
    }

    _createMenu() {
        let { height, type } = this.props;
        height = height ? height : Dimensions.get('window').height * 0.6
        const modalBoxStyle = [styles.modalBoxStyles];
        modalBoxStyle.push({
            width:  Dimensions.get('window').width
        })
        if (type == 2) {
            modalBoxStyle.push({ backgroundColor: Color.background })
        }
        modalBoxStyle.push({height:height})
        return (<View style={modalBoxStyle}>
            {this._createItem()}
            {this._bottomItem()}
        </View>);
    }

    _onPress(index){
        this.setState({
            index : index
        });
        if(this.props.style == 'radio' && this.props.type==1){
            this._close();
        }
        if(typeof this.props.onPress ==  'function' && this.props.type==1){
            this.props.onPress(this.state.index,this.state.data[this.state.index]['label'],this.state.data[this.state.index]['value']);
        }
    }

    _onPressIn(index) {
        this.setState({
            pressIndex: index,
            pressFlag : true
        });
    }

    _onPressOut() {
        this.setState({
            pressFlag : false
        });
    }

    _onCheckBoxChange(checked,value) {
        let index = null;
        let dataTmp = this.state.data;
        if(this.props.type==1){
            for (let i = 0; i < dataTmp.length; i++) {
                if (dataTmp[i].value == value) {
                    index = i;
                    break;
                }
            }
            dataTmp[index].checked = checked;
        }else if(this.props.type==2){
            for (var i = 0; i < dataTmp.length; i++) {
                for(var k=0;k<dataTmp[i].item.length;k++){
                    if(dataTmp[i].item[k].value == value){
                        dataTmp[i].item[k].checked = checked;
                    }
                }
            }
        };

        this.setState({
            data : dataTmp
        })
    }

    _onReset(){
        let dataTmp = this.state.data;
        if(this.props.type==1){
            dataTmp.map((item,i)=>{
                item.checked = false;
            });
        }else if(this.props.type==2){
            dataTmp.map((current,i)=>{
                return current.item.map((item)=>{
                    item.checked = false;
                })
            });
        }

        this.setState({
            data:dataTmp,
        });
        if(typeof this.props.onReset == 'function'){
            this.props.onReset();
        }
    }

    _onConfirm(){
        let checkedArr = [];
        if(this.props.style == 'checkbox'){
            if(this.props.type==1){
                this.props.data.map((item,index)=>{
                    if(item.checked){
                        checkedArr.push(item.value);
                    }
                });
            }else if(this.props.type==2){
                this.props.data.map((current,index)=>{
                    current.item.map((ele)=>{
                        if(ele.checked){
                            checkedArr.push(ele.value);
                        }
                    });
                });
            }
        }
        this._close();
        if(typeof this.props.onConfirm == 'function'){
            this.props.onConfirm(checkedArr);
        }
    }
    _onRequestClose(){
        this.setState({modalVisible:false})
    }
    render() {
        let { height } = this.props;
        height = height ? height : Dimensions.get('window').height * 0.6
        let modalVisible = this.state.modalVisible;
        const modalBoxStyle = [styles.modalBoxStyles];
        modalBoxStyle.push({
            height: height,
            width: Dimensions.get('window').width
        })
        let item = this._createMenu();

        let modalBackgroundStyle = {
            backgroundColor: 'rgba(0, 0, 0, 0.5)',
            flex:1
        };
        let modalWebStyle = {
            backgroundColor: 'white',
            flex:1
        };

        if(Platform.OS=="web"){
            return (
                <Modal
                    animationType='none'
                    transparent={true}
                    visible={this.state.modalVisible}
                    onRequestClose={()=>this._onRequestClose()}
                    >
                    <View>
                        <TouchableOpacity
                            activeOpacity={1}
                            underlayColor='transparent'
                            style={[{height: (Dimensions.get('window').height-height),backgroundColor:'rgba(0, 0, 0, 0.5)'}]}
                            onClick={()=>{
                                this.setState({modalVisible:false})
                            }}
                        >
                        </TouchableOpacity>
                        <View style={modalWebStyle}>
                            <View>
                                {item}
                            </View>
                        </View>
                    </View>
                </Modal>
            )
        }else{
            return (
                <Modal
                    animationType='none'
                    transparent={true}
                    visible={this.state.modalVisible}
                    onRequestClose={()=>this._onRequestClose()}
                    >
                    <TouchableOpacity activeOpacity={1} underlayColor='transparent' style={[styles.wrapper, Platform.OS == 'harmony' &&{ zIndex:1 }]}
                                      onLongPress={()=>{return false}}
                                      onPress={()=>{this.setState({modalVisible:false})}}>
                        <View style={modalBackgroundStyle}>
                            <View style={[styles.modalPos,{top:Dimensions.get('window').height-height}]}>
                                {item}
                            </View>
                        </View>
                    </TouchableOpacity>
                </Modal>
            )
        }
    };
};
Menu.propTypes = {
    //数据
    data: PropTypes.array,
    //默认值
    defaultIndex : PropTypes.number,
    //菜单类型，1一级菜单，2二级菜单
    type: PropTypes.number,
    //菜单样式，normal普通类型，radio单选样式，checkbox多选样式
    style: PropTypes.oneOf(['radio','checkbox']),
    //菜单高度
    width: PropTypes.number,
    //菜单高度
    height: PropTypes.number,
    //一级菜单对齐方式
    textAlign: PropTypes.oneOf(['left','center']),
    //选项点击事件
    onPress: PropTypes.func,
    //重置事件
    onReset: PropTypes.func,
    //确定事件
    onConfirm: PropTypes.func
};
Menu.defaultProps = {
    type:1,
    style:'radio',
    width: Dimensions.get('window').width,
    textAlign: 'left',
    data: [],
    // height: Dimensions.get('window').height * 0.6
};

const styles = StyleSheet.create({
    wrapper: {
        position: "absolute",
        backgroundColor: 'rgba(0, 0, 0, 0.4)',
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
        alignItems: 'center',
        justifyContent: 'center',
    },
    item: {
        height: 44,
        // width: Dimensions.get('window').width,
        backgroundColor: Color.white,
        borderBottomWidth: 1 / PixelRatio.get(),
        borderColor: Color.border,
        justifyContent: 'center',
        alignItems: 'center',
    },
    modalBoxStyles: {
        //height:containerHeight,
        // width:Dimensions.get('window').width,
        paddingBottom: 24
    },
    checkBoxItem: {
        flexDirection: 'column',
        height: 44,
        borderBottomWidth: 1 / PixelRatio.get(),
        borderBottomColor: Color.border,
        justifyContent: 'center',
        borderColor:Color.border,
    },
    buttonContainer: {
        flexDirection: 'row',
        position: 'absolute',
        bottom: 25,
        // width: Dimensions.get('window').width
    },
    button:{
        justifyContent:'center',
        alignItems:'center',
        flex:1,
        height:44,
        borderTopWidth:1 / PixelRatio.get(),
        borderBottomWidth:1 / PixelRatio.get(),
        borderColor:Color.border,
        backgroundColor:'white'
    },

    container:{
        flexDirection:'row'
    },
    leftMenuStyle:{
        borderWidth:1 / PixelRatio.get(),
        borderBottomWidth:0,
        borderRightWidth:0,
        borderColor:Color.border
    },
    rightMenuStyle: {
        borderWidth: 1 / PixelRatio.get(),
        borderBottomWidth: 0,
        borderLeftWidth: 0,
        // width: (Dimensions.get('window').width - 160),
        borderColor: Color.border
    },
    menuItemWidth:{
        width:160,
        borderColor:Color.border,
        backgroundColor:'rgba(229,229,229,0.4)',
    },
    listWidth: {
        // width: (Dimensions.get('window').width - 160)
    },
    dotStyle:{
        position: 'absolute',
        top: -10,
        right: -15,
    },
    modalPos: {
        position:'relative',
        backgroundColor:'white'
    },

});